package com.raychi.demo.servlet.company;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.raychi.demo.entity.Company;
import com.raychi.demo.util.CompanyUtil;
import com.raychi.demo.util.JdbcUtil;

public class CompanyUpdateServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		int id = Integer.valueOf(req.getParameter("id"));
		Company company = getCompanyById(id);
		req.setAttribute("company", company);
		req.getRequestDispatcher("/product/updateCompany.jsp").forward(req, resp);
	}
	
	private Company getCompanyById(int id) {
		Company company = null;
		Connection conn = null;
		try {
			conn = JdbcUtil.getConnection();
			Statement st = conn.createStatement();
			String sql = "select * from company where id=" + id;
			ResultSet rs = st.executeQuery(sql);
			while (rs.next()) {
				company = CompanyUtil.createCompany(rs);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (conn != null)
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
		}
		return company;
		
	}
	

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try{
			req.setCharacterEncoding("utf-8");
			String name = req.getParameter("name");
			int orderCount =Integer.valueOf(req.getParameter("orderCount"));
			int id = Integer.valueOf(req.getParameter("id"));
			updateCompany(name, orderCount, id);
			resp.sendRedirect(req.getContextPath() + "/company/");
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	private void updateCompany(String name, int orderCount, int id)
			throws SQLException, ClassNotFoundException {
		Connection conn = JdbcUtil.getConnection();
		String sql = "update company set name = ?,orderCount = ? where id =?";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setString(1, name);
		ps.setInt(2, orderCount);
		ps.setInt(3, id);
		ps.executeUpdate();
		conn.commit();
	}
	
}
